package com.hlt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlt.constant.MessageConstant;
import com.hlt.constant.PasswordConstant;
import com.hlt.constant.StatusConstant;
import com.hlt.dto.AdminDTO;
import com.hlt.dto.LoginDTO;
import com.hlt.dto.AdminPageQueryDTO;
import com.hlt.entity.Users;
import com.hlt.exception.AccountLockedException;
import com.hlt.exception.AccountNotFoundException;
import com.hlt.exception.PasswordErrorException;
import com.hlt.mapper.AdminMapper;
import com.hlt.result.PageResult;
import com.hlt.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.time.LocalDateTime;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Users> implements AdminService {

    private final AdminMapper adminMapper;

    public AdminServiceImpl(AdminMapper adminMapper) {
        this.adminMapper = adminMapper;
    }

    // 登录
    @Override
    public Users login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Users admin = adminMapper.selectOne(Wrappers.<Users>lambdaQuery().eq(Users::getUsername, username));

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (admin.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return admin;
    }

    /**
     * 新增
     * @param adminDTO
     */
    @Override
    public void save(AdminDTO adminDTO) {
        Users admin = new Users();
        admin.setUsername(adminDTO.getUsername());
        admin.setEmail(adminDTO.getEmail());
        admin.setPhone(adminDTO.getPhone());
        admin.setAge(adminDTO.getAge());
        admin.setSex(adminDTO.getSex());
        admin.setStatus(adminDTO.getStatus());
        admin.setRole(adminDTO.getRole());
        admin.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        admin.setCreatedAt(LocalDateTime.now());
        admin.setUpdatedAt(LocalDateTime.now());
        adminMapper.insert(admin);
    }

    /**
     * 分页查询
     * @param adminPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(AdminPageQueryDTO adminPageQueryDTO) {
        Page page = new Page(adminPageQueryDTO.getPageNum(), adminPageQueryDTO.getPageSize());
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(adminPageQueryDTO.getUsername() != null, Users::getUsername, adminPageQueryDTO.getUsername());
        queryWrapper.eq(adminPageQueryDTO.getRole() != null, Users::getRole, adminPageQueryDTO.getRole());
        page = page(page, queryWrapper);

        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * 根据id查询
     * @param userId
     * @return
     */
    @Override
    public Users getById(Long userId) {
        Users users = adminMapper.selectById(userId);
        users.setPassword("******");

        return users;
    }

    /**
     * 修改
     * @param adminDTO
     */
    @Override
    public void update(AdminDTO adminDTO) {
        Users admin = new Users();
        BeanUtils.copyProperties(adminDTO,admin);
//        admin.setUpdatedAt(LocalDateTime.now());
//        admin.setCreatedAt(LocalDateTime.now());
        // 确保 user_id 不为 null
        if (admin.getUserId() == null) {
            throw new IllegalArgumentException("User ID cannot be null for update operation.");
        }

        adminMapper.updateById(admin);
    }

    /**
     * 根据userid删除
     * @param userId
     */
    @Override
    public void removeById(Long userId) {
        adminMapper.deleteById(userId);
    }

    /**
     * 注册
     * @param loginDTO
     */
    @Override
    public void register(LoginDTO loginDTO) {
        Users admin = new Users();
        BeanUtils.copyProperties(loginDTO,admin);
        admin.setCreatedAt(LocalDateTime.now());
        admin.setUpdatedAt(LocalDateTime.now());
        admin.setStatus(StatusConstant.ENABLE);
        admin.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        admin.setRole(0);
        adminMapper.insert(admin);
    }


}
